<template>
  <div>
    <!-- 详情 -->
    <div>
      <FormPanel
        ref="formPanel"
        :list="formList"
        :cols="3"
        :formType="type"
        labelWidth="90"
        :isSubmitBtn="false"
      />
    </div>
    <div>
      <FilterTable
	      ref="table"
        height="auto"
        :dataSource="dataSource"
	      :columns="columns"
	      :onColumnsChange="columns => this.columns = columns"
	    >
        <template slot="controls">
          <el-button type="primary" v-if="type != 'show'" @click="addHendler">新增</el-button>
          <el-button :disabled="isChoice" type="primary" v-if="type != 'show'" @click="deleteHendler">删除</el-button>
        </template>
      </FilterTable>
    </div>
    <div style="margin-top: 15px;">
      <FormPanel
        ref="formPanel2"
        :list="formList2"
        :cols="2"
        :formType="type"
        labelWidth="90"
        :isSubmitBtn="false"
      />
    </div>
    <div>
      <FilterTable
	      ref="tableA"
        height="auto"
        :dataSource="serviceSource"
	      :columns="columnsA"
	      :onColumnsChange="columnsA => this.columnsA = columnsA"
	    >
        <template slot="controls">
          <el-button :disabled="dataSource.length===0" type="primary" v-if="type != 'show'" @click="addServicePrograms">新增</el-button>
          <el-button :disabled="isServiceChoice" type="primary" v-if="type != 'show'" @click="deleteServicePrograms">删除</el-button>
        </template>
      </FilterTable>
    </div>
    <div style="margin-top: 15px;">
      <FormPanel
        ref="formPanel3"
        :list="formList3"
        :cols="2"
        :formType="type"
        labelWidth="110"
        :isSubmitBtn="false"
      />
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
    	<el-button @click="toExamine" type="primary">审核</el-button>
      <el-button @click="closeDialog">返回</el-button>
    </div>
    <BaseDialog
	    :visible.sync="visible"
	    title="审核"
	    destroyOnClose
	    @close="closeDialogs"
	    :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
	  >
	    <toExamines :financialOrManager="financialOrManager" :rowData="formData" @close="closeHandler" @clos2="closeHandle2"></toExamines>
	  </BaseDialog>
    <Drawer
      :visible.sync="visible4"
      title="销售订单明细"
      :width="900"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <orderDetails :type="'show'" :baseData="formList" :rowData="formDetail" @close="closeHandler4" />
    </Drawer>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import toExamines from './toExamines'
import moment from 'moment'
import { quyOrders } from '@/api/retail/salesmanage/salesordermanage';
import orderDetails from '../salesorder/orderDetails'
export default {
  name: 'BuyingModal',
  components: {
    toExamines,
    orderDetails
  },
  mixins: [dictionary],
  props: {
    type: {
      type: String,
      default: 'show'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      formList: this.createFormList(), //上方明细数据
      formList2: this.createFormList2(), //下方数据车辆总价
      formList3: this.createFormList3(), //下方数据服务总价
      columns: this.createTableColumns(), //table数据
      columnsA: this.createTableColumnsA(), // 服务项目table数据
      dataSource: [], //table默认的值
      visible: false,
      visible4: false, // 销售订单明细
      clueData: {}, //线索数据
      formData: {},
      recordId: '',
      serviceSource: [], // 服务项目
      formDetail: {}, // 列表明细
      financialOrManager:null,
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      // 更新接口需要的记录 ID
      this.formData = this.rowData;
      this.recordId = this.rowData.soNoId;
      this.clueData.potentialCustomersId = this.rowData.customerId;
      this.ordeDetails()
    },
    ordeDetails (res){  //根据父组件传递的ID获取详细数据并赋值
      quyOrders(this.recordId).then(res => {
        if(res.resultCode == 200){
        res.data.sheetCreateDate = this.preDateHandler(res.data.sheetCreateDate);
        this.formList.forEach(x => {
          if(x.fieldName === 'consultant'){ // 特别处理
              this.EditConsultantId = Number(res.data['consultant']) == res.data['consultant'] ? res.data['consultant'] : res.data['consultantId'];
              x.initialValue = res.data[x.fieldName];
            } else if (x.fieldName === 'urls') {
              let urls = res.data['urls']
              let urlsList = urls.map(item => {
                let origin = item.split('/');
                let fileName = origin[origin.length-1];
                return { name: fileName, url: item};
              });
              x.initialValue.push(...urlsList)
            } else {
              x.initialValue = res.data[x.fieldName];
            }
          });
          this.formList2.forEach(x => x.initialValue = res.data[x.fieldName]);
          this.dataSource = res.data.vehicleList;
          // 显示第一个数据的服务项目
          this.dataSource.forEach(item => {
            item['showService'] = false
          })
          this.dataSource[0]['showService'] = true
          this.serviceSource = this.dataSource[0]['serviceItem']
          // 计算服务项目费用
          this.amountAmount()
          console.log(this.dataSource)
          this.orderInfo = res.data;
        }
      });
    },
    createFormList() { //上方明细数据
      return [
        {
          type: 'INPUT',
          label: '客户订单号',
          fieldName: 'soNo',
          placeholder: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '客户编号',
          fieldName: 'customerNo',
          placeholder: '请选择...',
          readonly: 'readonly',
          disabled: true,
          unitRender: () => {
	        	return <el-button slot="append" icon="el-icon-search"></el-button>;
	        },
        },
        {
          type: 'SELECT',
          label: '订单状态',
          disabled: false,
          fieldName: 'soStatus',
          placeholder: '请选择...',
          disabled: true,
          initialValue: 14041001,
          itemList: this.createDictList('1404'),
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'customerName',
          placeholder: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '手机号码',
          fieldName: 'mobilePhone',
          placeholder: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '销售顾问',
          fieldName: 'consultant',
          placeholder: '', // TODO:当前登录账号
          disabled: true,
          // initialValue: this.rowData.consultantId,
          // itemList: [],
        },
        {
          type: 'SELECT',
          label: '证件类型',
          fieldName: 'ctCode',
          placeholder: '请选择',
          itemList: this.createDictList('1508'), // 原'1058'修改为'7035' 再改为'1508'
        },
        {
          type: 'INPUT',
          label: '证件号码',
          fieldName: 'certificateNo',
          placeholder: '',
          rules: []
        },
        {
          type: 'INPUT',
          label: '联系地址',
          fieldName: 'address',
          placeholder: '',
          selfCols: 2,
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '开单日期',
          fieldName: 'sheetCreateDate',
          placeholder: '',
          disabled: true,
          initialValue: this.preDateHandler(new Date()),
        },
        {
          type: 'SELECT',
          label: '支付方式',
          fieldName: 'payMode',
          placeholder: '请选择...',
          initialValue: 14261001,
          itemList: this.createDictList('1426'),
        },
        {
          type: 'SELECT',
          label: '开票方式',
          fieldName: 'invoiceMode',
          placeholder: '请选择...',
          initialValue: 14291001,
          itemList: this.createDictList('1429'),
        },
        {
          type: this.type === 'add'?'SELECT':'INPUT',
          label: '开单人',
          fieldName: 'sheetCreatedBy',
          placeholder: '',
          disabled: true,
          initialValue: '',
          itemList: [],
        },
        {
          type: 'SELECT',
          label: '交车方式',
          fieldName: 'deliveryMode',
          placeholder: '请选择...',
          initialValue: 14281001,
          itemList: this.createDictList('1428'),
        },
        {
          type: 'SELECT',
          label: '车辆用途',
          fieldName: 'vehicleUse',
          placeholder: '请选择...',
          itemList: this.createDictList('1511'),
        },
        {
          type: 'INPUT',
          label: '合同编号',
          disabled: false,
          fieldName: 'contractNo',
          placeholder: '',
          // rules: [{ pattern: /^[a-zA-Z0-9]+$/, message: '请输入字母或数字', trigger: 'blur' }],
        },
        {
          type: 'INPUT_NUMBER',
          label: '合同定金',
          disabled: false,
          fieldName: 'contractEarnest',
          placeholder: '',
          // rules: [{ pattern: /[\d]+/g, message: '请输入数字', trigger: 'blur' }],
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'remark',
          selfCols: 2,
          maxlength: 32,
          placeholder: '',
        },
        {
          type: 'UPLOAD_FILE',
          label: '上传文件',
          fieldName: 'urls',
          selfCols: 3,
          placeholder: '上传文件...',
          style: {width: '300px'},
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 2,
            tipText: '最多上传2个附件'
          }
        }
      ];
    },
    createFormList2 (){ //底部数据
      return [
        {
          type: 'INPUT',
          label: '购车总数量',
          fieldName: 'vehicleSum',
          disabled: true,
          placeholder: '',
          initialValue: 0,
        },
        {
          type: 'INPUT',
          label: '购车总金额',
          fieldName: 'orderSum',
          disabled: true,
          placeholder: '',
          initialValue: 0,
        }
      ]
    },
    createFormList3 () { //底部数据服务总价
      return [
        {
          type: 'INPUT',
          label: '服务项目总金额',
          fieldName: 'serviceSum',
          disabled: true,
          placeholder: '',
          initialValue: 0,
        },
        {
          type: 'INPUT',
          label: '客户订单总金额',
          fieldName: 'totalSum',
          disabled: true,
          placeholder: '',
          initialValue: 0,
        }
      ]
    },
    createTableColumns (){ //表格数据
      const _this = this
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 200,
          fixed: 'left',
          render: (props, h) => {
            let operateList = []
            let detailBtn = <el-button size="mini" disabled={props.row['showService']} type="text" onClick={props.row['showService']?'':() => this.detailedHandle(props.row)}>
                            服务
                          </el-button>
            let showBtn = <el-button size="mini" type="text" onClick={() => this.modifyHandle(props.row)}>
                            明细
                          </el-button>
            let verticalElement = <el-divider direction="vertical" />
            operateList = [
              detailBtn,verticalElement,
              showBtn
            ]
            return (<div>{operateList}</div>);
          }
        },
        {
	        title: '序号',
	        dataIndex: 'index',
	        width: 80,
	        render: props => {
	          return <span>{props.row.index + 1}</span>;
	        }
	      },
	      {
	        title: '销售订单号',
          dataIndex: 'viNo',
          width: 150,
	        filterType: 'input',
	      },
	      {
	        title: 'VIN',
	        dataIndex: 'salesVin',
	        filterType: 'input',
	      },
	      {
	        title: '开票名称',
	        dataIndex: 'customerName', // invoiceName => customerName
	        filterType: 'input',
	      },
	      // {
	      //   title: '开票联系人',
	      //   dataIndex: 'invoiceLinkMan',
	      //   filterType: 'input',
	      // },
	      // {
	      //   title: '开票电话',
	      //   dataIndex: 'invoiceMobile',
	      //   filterType: 'input',
	      // },
	      // {
	      //   title: '开票地址',
	      //   dataIndex: 'invoiceAddress',
	      //   filterType: 'input',
	      // },
	      {
	        title: '产品代码',
          dataIndex: 'productCode',
          width: 235,
	        filterType: 'input',
	      },
	      {
	        title: '品牌',
	        dataIndex: 'brandName',
	        filterType: 'input',
	      },
	      {
	        title: '车系',
	        dataIndex: 'seriesName',
	        filterType: 'input',
	      },
	      {
	        title: '车型',
	        dataIndex: 'modelName',
	        filterType: 'input',
	      },
	      {
	        title: '配置',
          dataIndex: 'packageName',
          width: 230,
	        filterType: 'input',
	      },
	      {
	        title: '颜色',
          dataIndex: 'color',
          width: 115,
	        filterType: 'input',
	      },
	      {
	        title: '预交车日期',
          dataIndex: 'deliveringDate',
          width: 200,
          render: props => {
            return <span>{ this.preDateHandler(props.row.deliveringDate,'YYYY-MM-DD') }</span>
          }
	      },
	      {
	        title: '销售单价',
	        dataIndex: 'vehiclePrice',
	        filterType: 'input',
	      },
	      {
	        title: '配车状态',
	        dataIndex: 'dispatchedStatus',
	        filterType: 'input',
          filterItems: this.createDictList('1414'),
          render: props => {
            return <span>{this.createDictText(props.row.dispatchedStatus, '1414')}</span>;
          }
	      }
      ]
    },
    createTableColumnsA () {
      return [
        {
	        title: '序号',
	        dataIndex: 'index',
	        width: 80,
	        render: props => {
	          return <span>{props.row.index + 1}</span>;
	        }
        },
	      {
	        title: '项目代码',
          dataIndex: 'serviceCode',
	        filterType: 'input',
	      },
	      {
	        title: '项目名称',
          dataIndex: 'serviceName',
	        filterType: 'input',
	      },
	      {
	        title: '费用类型',
          dataIndex: 'serviceType',
	        filterType: 'input',
          filterItems: this.createDictList('1421'),
          render: props => {
            return <span> { this.preDictHandler(props.row.serviceType,'1421')} </span>
          }
	      },
	      {
	        title: '费用金额',
          dataIndex: 'actualSellPrice',
	        filterType: 'input',
	      },
      ]
    },
    detailedHandle (row){ // 服务项目查看
      console.log('服务项目查看',row)
      // 切换前存数据
      try{
        // TODO:点地保存可能需要重复此操作
        this.dataSource.find(item => item['showService'] === true)['serviceItem'] = JSON.parse(JSON.stringify(this.serviceSource))
      } catch (e){
      }
      this.dataSource.forEach(item => {
        item['showService'] = false
      })
      this.dataSource[row.$index]['showService'] = true
      // 表单重现数据step.1
      this.serviceSource = this.dataSource[row.$index]['serviceItem']
    },
    amountAmount (){ //计算数量和价格
      let [orderSum,serviceSum,totalSum] = [0,0,0];
      let dataSourceLength = this.dataSource.length
      for(let i = 0; i < dataSourceLength; i++){
        orderSum = parseInt(this.dataSource[i].vehiclePrice) + parseInt(orderSum)
        let serviceItemLength = this.dataSource[i].serviceItem.length
        for (let k = 0; k < serviceItemLength; k++) {
          serviceSum += (this.dataSource[i].serviceItem[k].actualSellPrice || 0)
        }
      }
      totalSum = orderSum + serviceSum
      // 购车数目
      this.formList2.find(item => item.fieldName === 'vehicleSum').initialValue = this.dataSource.length
      // 购车总金额
      this.formList2.find(item => item.fieldName === 'orderSum').initialValue = orderSum
      // 服务项目总金额
      this.formList3.find(item => item.fieldName === 'serviceSum').initialValue = serviceSum
      // 客户订单总金额
      this.formList3.find(item => item.fieldName === 'totalSum').initialValue = totalSum
    },
    closeHandler (val){ //弹框返回
      this.visible = val;
    },
    closeDialog(param) { //抽屉返回
      this.$emit('close', false);
    },
    closeHandler4() {//销售单明细
      this.visible4 = false;
    },
    closeHandle2 (val){ //整体返回
      this.visible = val;
      this.$emit('close', false);
    },
    toExamine (){ //弹出审核界面
      this.visible = true;
      this.financialOrManager =1
    },
    modifyHandle (row){ // 销售单修改
      console.log('modifyHandle',row)
      this.visible4 = true;
      this.formDetail = row
    },
    closeDialogs (val){
    	this.visible = val
    },
    // 字典数据使用前预处理
    preDictHandler(val, code){
      let resultText = val && String.prototype.includes.call(val, code) ? this.createDictText(val, code) : val;
      return resultText;
    },
    // 日期预处理
    preDateHandler(val, formatCode='YYYY-MM-DD HH:mm:ss') {
      let resultDate = val ? moment(Number(val)).format(formatCode) : val;
      if ((resultDate == 'Invalid date' || resultDate == 'Invalid Date') && val) {
        resultDate = moment(val).format(formatCode)
      }
      return resultDate;
    },
  }
};
</script>

<style lang="less" scoped>
</style>
